package com.front.web.member;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.redisUtils.JedisUtils;
import com.bootdo.common.utils.DateUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.haojiangboutils.MapBuild;
import com.bootdo.lvyou.domain.LvyouCity;
import com.bootdo.mall_part.domain.MallHousePlot;
import com.bootdo.mall_part.domain.StatusNumberVo;
import com.bootdo.member.commons.MemberIntegralsUtils;
import com.bootdo.member.domain.ShequIntegralRecord;
import com.bootdo.member.domain.ShequMember;
import com.bootdo.member.service.ShequIntegralRecordService;
import com.front.web.commons.AvoidRepeatableCommit;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;

@RestController
@RequestMapping("/f/shequ/SheQuMemberController/")
public class SheQuMemberController extends MemberSuperController{

    /**
     * APP  注册(已完成-----需要社区表----加上名称 城市)
     * @param shequMember 用户对象
     * @param code 验证码
     * @return
     */
    @RequestMapping("register")
    public R register(ShequMember shequMember, @RequestParam(value = "code",defaultValue = "")String code,
                      @RequestParam(value = "password",defaultValue = "")String password){
            if(shequMember.getMobile()==null){
                return R.error("请输入手机号码");
            }

            if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + shequMember.getMobile()))) {
                return R.error("验证码错误!");
            }
        //缺少社区表  将社区绑定到用户    默认社区策略
        Long communityId = shequMember.getCommunityId();
        MallHousePlot mallHousePlot = mallHousePlotService.get(communityId);
        shequMember.setRealName(shequMember.getRealName());
        shequMember.setCityId(mallHousePlot.getCityId());
        shequMember.setCityName(mallHousePlot.getCityName());
        shequMember.setCommunityId(communityId);
        shequMember.setIntegral(0.00);
        shequMember.setCommunityName(mallHousePlot.getName());
        shequMember.setPassword(DigestUtils.sha256Hex(password));
        int save = shequMemberService.save(shequMember);
        if(save>0){
            shequMember.setPassword("");
        }

        return R.ok().put("i",shequMember);
    }

    /**
     * 登录功能
     * @param mobile    手机号码  账号
     * @param code      验证码（手机号登录时需要）
     * @param password  密码（账号密码登录时需要）
     * @return
     */
    @RequestMapping("login")
    public R login(@RequestParam("mobile")String mobile,
                   @RequestParam(value = "code",defaultValue = "")String code,
                   @RequestParam(value="password",defaultValue = "")String password){
        ShequMember shequMember = shequMemberService.getByMobile(mobile);
        if(shequMember==null){
            return R.error("账号不存在，请注册");
        }
        if(StringUtils.isNotBlank(code)){
            if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
                return R.error("验证码错误!");
            }
        }else{
          /*  shequMember = shequMemberService.selectMobileAndPassWord(mobile, password);*/
            String SysPassword = shequMember.getPassword();
            if(!SysPassword.equals(DigestUtils.sha256Hex(password))){
                return R.error("密码错误，请重新输入");
            }
        }

        // 进行redis 的缓存处理
        JedisUtils.set(DigestUtils.sha256Hex(mobile), JSON.toJSONString(shequMember), 60*60*24*20);

        shequMember.setPassword(null);
        return R.ok("登录成功").put("i",shequMember);
    }

    /**
     * APP登出
     * @param mobile
     * @return
     */
    @RequestMapping("loginOut")
    public R loginOut(@RequestParam("mobile")String mobile ){

        try {

            JedisUtils.del(DigestUtils.sha256Hex(mobile));
        }catch (Exception e){

            return R.error("退出失败");
        }

        return R.ok();
    }


    /**
     * 修改会员信息（未完成  需要知道修改内容）
     * @param sheQuMember
     * @param mobile
     * @return
     */
    @RequestMapping("updateMemberInfo")
    public R  updateMemberInfo(ShequMember sheQuMember,
            @RequestParam("mobile")String mobile){

        ShequMember member = shequMemberService.getByMobile(mobile);

        member.setAvatar(sheQuMember.getAvatar());
        int save = shequMemberService.save(member);


        if (save>0){
            return R.ok();

        }

        return R.error("修改失败");
    }

    /**
     * 三级联动  城市选择
     * @param parentId
     * @return
     */
    @RequestMapping("getCityAllByParentId")
    public R getCityAllByParentId(@RequestParam(value = "parentId",defaultValue = "0")Long parentId){
        List<LvyouCity> list=null;
        if(parentId==0){
            HashMap<String, Object> map = new HashMap<>();
            map.put("gradeNumber",1);
            list= lvyouCityService.list(map);

        }else{
           list = lvyouCityService.getByParent(parentId);
        }

            return R.ok().put("i",list);
    }


    /**
     * 获取城市 三级联动 数据格式（弃用）
     * @return
     */
    @RequestMapping("getCityAll")
    public R getCityAll(){
        HashMap<String, Object> param = new HashMap<>();
        param.put("gradeNumber","1");
        List<LvyouCity>  list= lvyouCityService.list(param);
        for(LvyouCity city:list){
           recursion(city);
        }
        return R.ok().put("i",list);

    }

    public LvyouCity recursion(LvyouCity city){

        List<LvyouCity> byCityId = lvyouCityService.getByParent(city.getId().longValue());
        if(byCityId!=null){
            city.setChildren(byCityId);
            for (LvyouCity lvyouCity:byCityId){
                recursion(lvyouCity);
            }
            return  null;
        }else{
            return  city;
        }


    }

    /**
     * 获取小区
     * @return
     */
    @RequestMapping("getMallHouseByCityId")
    public R getMallHouseByCityId(@RequestParam(value = "cityId",defaultValue = "")Long cityId,@RequestParam(value = "name",defaultValue = "")String name){
       /* List<MallHousePlot> list=null;
        if(cityId==null){
            list = mallHousePlotService.getByName(name);

        }else{

            list = mallHousePlotService.getByCityIdAndName(cityId,name);
            MallHousePlot cityDefault = mallHousePlotService.getCityDefault(cityId);
            list.add(0,cityDefault);
        }*/
        HashMap<String, Object> map = new HashMap<>();
        List<MallHousePlot> list=null;
        if(cityId!=null){
            map.put("cityId",cityId);
            map.put("name",name);
            map.put("houseFlag","1");
            map.put("delFlag","1");
            map.put("order","asc");
            map.put("sort","type");
            list = mallHousePlotService.list(map);
        }


        if(list==null){
            return R.error("暂无数据");
        }
        return R.ok().put("i",list);
    }

    /**
     * 修改密码（根据旧密码修改新密码）
     * @param oldPassword
     * @param newPassword
     * @return
     */
    @RequestMapping("updatePassword")
    public R updatePassword(@RequestParam("mobile")String mobile,
                            @RequestParam("oldPassword")String oldPassword,
                            @RequestParam("newPassword")String newPassword){

        ShequMember byMobile = shequMemberService.getByMobile(mobile);
        String password = byMobile.getPassword();
        if(password.equals(DigestUtils.sha256Hex(oldPassword))){
            byMobile.setPassword(DigestUtils.sha256Hex(newPassword));
            shequMemberService.save(byMobile);
            return R.ok("修改密码成功");
        }

        return  R.error("密码错误");

    }

    /**
     * 修改密码（根据短信验证码修改密码）
     * @param newPassword
     * @return
     */
    @RequestMapping("setNewPassword")
    public R setNewPassword(@RequestParam("mobile")String mobile,
                            @RequestParam("code")String code,
                            @RequestParam("newPassword")String newPassword){

        ShequMember member = shequMemberService.getByMobile(mobile);
        if(member==null){
            return R.error("用户不存在，请注册");
        }
        if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
            return R.error("验证码错误!");
        }

        member.setPassword(DigestUtils.sha256Hex(newPassword));
        shequMemberService.save(member);
        return R.ok("修改密码成功");

    }
    /**
     * 修改密码 短信验证
     * @param code
     * @param mobile
     * @return
     */
    @RequestMapping("noteCheck")
    public R noteCheck(@RequestParam("code")String code,
                            @RequestParam("mobile")String mobile){
        if (!code.equals(JedisUtils.get(SendMobileMessageController.CODEKEY + mobile))) {
            return R.error("验证码错误!");
        }

        return R.ok();

    }

    /**
     * 积分兑换物业费 消息通知（客户端）列表
     * @param memberId
     * @return
     */
    @RequestMapping("notificationMessages")
    public R notificationMessages(@RequestParam("memberId") Long memberId,@RequestParam("pageNo")Integer pageNo,
                                  @RequestParam("pageSize")Integer pageSize){


        HashMap<String, Object> param = new HashMap<>();
        param.put("memberId",memberId);
        List<ShequIntegralRecord> isListByState = shequIntegralRecordService.list(param);
        boolean flag=true;
        for(ShequIntegralRecord record:isListByState){
            if( record.getState()==0){
                flag=false;
            }

        }
        if(flag){
            param.put("sort","create_time");
            param.put("order","desc");
        }
        param.put("offset",pageNo*pageSize);
        param.put("limit",pageSize);
        List<ShequIntegralRecord> list = shequIntegralRecordService.list(param);

        return R.ok().put("i",list);
    }
    /**
     * 积分兑换物业费 消息通知 确认或拒绝操作
     * @param mobile   电话
     * @param recordId   记录id
     * @param type    操作类型  1同意  其他为不同意
     * @return
     */
    @AvoidRepeatableCommit
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping("updateIntegrals")
    public R updateIntegrals(@RequestParam("mobile") String mobile,@RequestParam(value = "recordId",defaultValue = "")Long recordId,
                             @RequestParam(value = "type",defaultValue = "")int type){//  type  等于1的话 为 同意   其他为不同意
        ShequIntegralRecord shequIntegralRecord = shequIntegralRecordService.get(recordId);
        if(shequIntegralRecord.getState()==3){
            return R.error("兑换操作已被取消");
        }
        if(shequIntegralRecord.getState()!=0){
            return R.error("请勿重复操作");
        }

        return shequIntegralRecordService.updateIntegrals(mobile,type,shequIntegralRecord);


    }


    /**
     * 得到订单数量
     * http://127.0.0.1:8090/f/shequ/SheQuMemberController?memberMobile=15230060935
     * @return
     */
    @RequestMapping("dataStatistics")
    public R getOrderList(
            @RequestParam("memberMobile") String memberMobile){

        ShequMember byMobile = shequMemberService.getByMobile(memberMobile);
        if(byMobile==null){
            return R.ok().put("orderNumber",  0).put("integral",0);
        }
        MapBuild mapBuild = new MapBuild();
        mapBuild.setKV("memberMobile", memberMobile);
        int count =  mallOrderService.count(mapBuild);

        List<StatusNumberVo> list = mallOrderService.statusCount(mapBuild);
        Map<String, Object> resultMap = new HashMap<>();

        for (int i = 1; i <= 3; i++) {
           resultMap.put(i + "", 0);

        }

        for (StatusNumberVo one: list) {
            resultMap.put(one.getStatus(), one.getNumber());
        }

        return R.ok(resultMap).put("orderNumber",  count).put("integral",byMobile.getIntegral()).put("yizhifu", resultMap.get("1")).put("yifahuo", resultMap.get("2")).put("yishouhuo", resultMap.get("3"));
    }


}
